package com.xm.exception;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * 拦截所有请求报错
 *
 * @author 康文程
 * @date 2023-12-4 下午 05:20
 */
@WebFilter(urlPatterns = {"/*"})
public class ErrorException implements Filter {
    /**
     * 初始
     *
     * @param filterConfig a <code>FilterConfig</code> object containing the
     *                     filter's configuration and initialization parameters
     */
    @Override
    public void init(FilterConfig filterConfig) {
    }

    /**
     * 显示报错信息跳转页面
     *
     * @param request  the <code>ServletRequest</code> object contains the client's request
     * @param response the <code>ServletResponse</code> object contains the filter's response
     * @param chain    the <code>FilterChain</code> for invoking the next filter or the resource
     * @throws IOException      捕抓跳转报错
     * @throws ServletException 捕抓报错信息
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            // 执行其他过滤器或目标资源
            chain.doFilter(request, response);
        } catch (Throwable e) {
            // 打印异常信息
            System.out.println("\033[31m 报错信息 : " + e.getMessage() + " \033[0m");

            request.setAttribute("state",500);
            request.setAttribute("information","哎呀! 服务器错误。请稍后再试。");

            request.getRequestDispatcher("/WEB-INF/page/exception.jsp").forward(request,response);

        }
    }

    /**
     * 销毁
     */
    @Override
    public void destroy() {
    }
}
